function [s_hat,signal] = sphere_detector_bpsk(h,r,rho,nt,nr)


constellation_size=2;
[q,u]=qr(h);

s_tilde=sqrt(nt/rho)*inv(h'*h)*h'*r;
init_point=exp(j*-3*pi/4)*ones(nt,1);
radius=get_euclidean_distance(s_tilde,100000*init_point)+1;	%added 1 to allow for the equals case

tree=zeros(nt,constellation_size);
s_hat=init_point;
counter=0;
while(sum(sum(tree))~=nt  & counter<4000)
counter=counter+1;
tree=zeros(nt,constellation_size);
i=nt;
s_hat=zeros(nt,1);
while(i>0)
	[s_possible,s_min]=full_equation2(u,s_hat,s_tilde,nt,i,radius);
	if(s_min==-1)
		flag=0;
		while(flag==0)
			i=i+1;
			[s_hat(i),flag,tree]=retreat_tree_bpsk(s_hat,tree,i)
		end
		i=i-1;
	else
		tree(i,s_possible)=1;
		s_hat(i)=s_min;
		i=i-1;
	end
end
if(get_euclidean_distance(s_tilde,s_hat)<radius)
	s_final=s_hat;
	radius
	radius=get_euclidean_distance(s_tilde,s_hat)
end
tree
radius
end
if(counter==4000)
s_hat=s_final;
end

signal=[];
for m=1:length(r)
	signal=horzcat(signal,bpsk2bin(s_hat(m)));
end







function [s_possible,s_min]=full_equation2(u,s_hat,s_tilde,nt,start,radius)

theta=[pi 0];
s_try=exp(j*theta);
new_s_hat=s_hat;
for k=1:length(s_try)
	new_s_hat(start)=s_try(k);
	test_radius(k)=get_euclidean_distance(s_tilde(start:nt),new_s_hat(start:nt));
end
radius
test_radius
s_possible=find(test_radius<=radius);
if(length(s_possible)>0)
	[minimum,s_min]=min(test_radius);
	s_min=s_try(s_min);
	s_min=s_try(s_possible(ceil(rand*length(s_possible))));
else
	s_min=-1;
end




function radius=get_euclidean_distance(r,r_hat)
radius=norm(abs(r-r_hat));
